package com.bw.module_home.device.viewmodel

import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.bw.lib_common.base.BaseViewModel
import com.bw.module_home.device.model.DeviceEntity
import com.bw.module_home.device.model.DeviceEntityItem
import com.bw.module_home.device.model.DeviceRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import javax.inject.Inject

@HiltViewModel
class DeviceViewModel @Inject constructor(
    private val deviceRepository: DeviceRepository
) : BaseViewModel() {

    val getDeviceSuccess = MutableLiveData<List<DeviceEntity>>()
    val addDeviceSuccess = MutableLiveData<List<DeviceEntityItem>>()

    fun deviceList() {
        deviceRepository.getDeviceList()
            .onEach { result ->
                if (result.code == 200) {
                    result.data?.let {
                        // 更新 LiveData 的值
                        val currentList = getDeviceSuccess.value?.toMutableList() ?: mutableListOf()
                        currentList.add(it)
                        getDeviceSuccess.value = currentList
                    }
                } else {
                    Log.e("DeviceViewModel", "获取设备列表失败  ${result.message}")
                }
            }
            .catch { e ->
                Log.e("DeviceViewModel", "获取设备列表异常: ${e.message}")
            }
            .launchIn(viewModelScope)
    }

    fun addDevice(deviceEntityItem: DeviceEntityItem) {
        deviceRepository.addDevice(deviceEntityItem)
            .onEach { result ->
                Log.d("add_device", "addDevice:${result.data}")
                if (result.code == 200) {
                    result.data?.let {
                        // 更新 LiveData 的值
                        val currentList = addDeviceSuccess.value?.toMutableList() ?: mutableListOf()
                        currentList.add(it)
                        addDeviceSuccess.value = currentList
                    }
                } else {
                    Log.e("DeviceViewModel", "添加设备失败 ${result.message}")
                }
            }
            .catch { e ->
                Log.e("DeviceViewModel", "添加设备异常: ${e.message}")
            }
            .launchIn(viewModelScope)
    }

    //错误信息提示
    val mErrorLiveData  = MutableLiveData<String>()
}